import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators.rest import restrict

from sc_console.lib.base import BaseController, render

from sc_console.model.meta import Session
from sc_console.model.models import YouTubePartialParse, RawMessage

log = logging.getLogger(__name__)

YOUTUBE_MANUAL_PARSE_MESSAGE = 'sc_engine.apps.messages.YouTubeManualParseAnnouncement'
YOUTUBE_RETRY_MESSAGE = 'sc_engine.apps.messages.YouTubeVideoFetchRequested'

class YouTubePartialParseController(BaseController):
    def index(self):
        c.partial_parses = Session.query(YouTubePartialParse)\
                .order_by(YouTubePartialParse.time.desc()).all()
        return render('/partial_parse/youtube_index.mako')

    def _get_parse(self, video_id):
        return Session.query(YouTubePartialParse)\
                .filter(YouTubePartialParse.video_id == video_id).one()
    
    def view(self):
        id = request.urlvars['id']

        c.parse = self._get_parse(id)
        return render('/partial_parse/youtube_view.mako')

    def retry_command(self):
        video_id = request.urlvars['id']

        parse = self._get_parse(video_id)

        data = {'video_id' : video_id}
        rm = RawMessage(message_name=YOUTUBE_RETRY_MESSAGE, data=data)

        Session.add(rm)
        Session.delete(parse)
        Session.commit()

    def retry(self):
        self.retry_command()

        return redirect_to(controller='you_tube_partial_parse', action='index')

    def delete_command(self):
        video_id = request.urlvars['id']

        parse = self._get_parse(video_id)

        Session.delete(parse)
        Session.commit()

    def delete(self):
        self.delete_command()

        return redirect_to(controller='you_tube_partial_parse', action='index')

